import {Component, OnInit} from '@angular/core';
import {_HttpClient} from '@delon/theme';
import {Router} from '@angular/router';
import {UtilityService} from '../../../service/utils.service';
import {SystemModule} from '../../../service/system';
import {appConfig} from '../../../service/common';
import {NzModalService, NzNotificationService} from 'ng-zorro-antd';

@Component({
    selector: 'app-system',
    templateUrl: './system.component.html',
    styleUrls: ['./system.component.less']
})
export class SystemComponent implements OnInit {

    constructor(
        private http: _HttpClient,
        private router: Router,
        private utilityService: UtilityService,
        private modal: NzModalService,
        private nznot: NzNotificationService
    ) {

    }

    system: SystemModule = new SystemModule(); // 搜索值

    sysAdd: SystemModule = new SystemModule(); // 新增内容

    loading = false;
    expandForm = false;
    isshow: boolean = false; // 默认是false 不显示
    isEdit = false; // 是否是修改，默认不是
    sysTitle: string; // 弹出框标题
    // 应用
    guidApp: any;
    // 值来源类型:
    valueFrom = [
        { text: '手动输入', value: false, key: 'H' },
        { text: '业务字典', value: false, key: 'D' },
    ];
    pageIndex = 1;
    // 业务字典
    dictKey = [
        { dictName: '账户类型', value: false, guid: '1029295511309471745' },
        { dictName: '交易状态', value: false, guid: '1029290035100340225' },
        { dictName: '角色分组', value: false, guid: '1029673332138020866' },
        { dictName: '机构类型', value: false, guid: '1029313834529148929' },
    ]
    selectedRows: any; // 选中的总数
    // 参数值
    configValue: any;
    isValueshow = false; // 默认是false
    modalVisible = false;

    data: any[] = []; // 表格数据
    headerData = [  // 配置表头内容
        { value: '应用系统', key: 'appName', isclick: false },
        { value: '参数组别', key: 'groupName', isclick: false },
        { value: '参数键', key: 'keyName', isclick: false },
        { value: '值来源', key: 'valueFromCopy', isclick: false },
        { value: '参数值', key: 'value', isclick: false },
        { value: '参数描述', key: 'description', isclick: false },
    ];

    moreData = {
        morebutton: true,
        buttons: [
            { key: 'Overview', value: '查看概况' }
        ]
    }
    test: string;
    page: any;
    total: number;
    configTitle: any;

    // 表头按钮
    buttons = [
        {key: 'add', value: '新增运行参数', buttonCode: appConfig.funcObject.system.addSys}
    ]

    ngOnInit() {
        this.getData(); // 只会触发一次，但是ngchanges并不会触发咋办
        this.generateFakeData();
        this.configTitle =  { value: '修改', buttonCode: appConfig.funcObject.system.editSys}
    }

    // 父组件初始化数据
    getData(option?) { // 初始化请求后台数据
        if(option) {
            this.pageIndex = 1;
        }
        this.page = {
            condition: option, // 搜索内容
            page: {
                current: this.pageIndex,
                size: this.system.size,
            }
        };
        this.utilityService.postData(appConfig.serverUrl + appConfig.API.sysConfigsList, this.page)
            .subscribe(
                (val) => {
                    for (let i = 0; i < val.result.records.length; i++) {
                        if (val.result.records[i].valueFrom === 'H') {
                            val.result.records[i].valueFromCopy = '手动输入';
                        } else {
                            val.result.records[i].valueFromCopy = '业务字典';
                        }
                        val.result.records[i].buttonData = [{key: 'dels', value: '删除', buttonCode: appConfig.funcObject.system.delSys}];
                    }
                    this.data = val.result.records;
                    this.total = val.result.total;
                }
            );
    }

    // 查询所有应用, 打开弹窗的时候调用
    queryApplist() {
        this.utilityService.getData(appConfig.serverUrl + appConfig.API.appListAll)
            .subscribe(
                (val) => {
                    this.guidApp = val.result;
                },
                response => {

                });
    }


    // 想一下，能否把这三个方法封装到一个ts里面，引入即可，不然每次都写着三个方法不太现实。
    // 列表组件传过来的内容
    addHandler(event) {
        console.log(event)
        this.queryApplist();
        this.generateFakeData();
        if (event === 'add') {
            for (const key in this.sysAdd) {
                delete this.sysAdd[key];
            }
            this.sysTitle = '新增运行参数';
            this.modalVisible = true;  // 此时点击了列表组件的新增，打开模态框
            this.isEdit = false;
        } else { // 代表修改，把修改的内容传递进去，重新渲染
            if (event.dictGuid) {
                this.checkSelect(event.dictGuid);
            }

            this.sysAdd = event;
            this.sysAdd.dictKey = event.dictGuid;
            // this.sysAdd.value = event.dictItemName;
            if (event.dictItemName) {
                this.isValueshow = true;
            }
            this.sysTitle = '修改运行参数';
            this.modalVisible = true;  // 此时点击了列表组件的新增，打开模态框
            this.isEdit = true;
        }
    }

    // 列表传入的翻页数据
    monitorHandler(event) {
        this.pageIndex = event;
        this.getData();
    }


    // 右侧按钮方法
    buttonEvent(e) {
        if (e.names) {
            if (e.names.key === 'dels') {
                this.deleatData(e);
            }
        }
    }


    // 接受子组件删除的数据 单条还是多条
    deleatData(event) {
        this.modal.open({
            title: '是否删除',
            content: '您是否确认删除所选数据?',
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
                this.utilityService.deleatData(appConfig.serverUrl + appConfig.API.sysConfigsDel + '/' + event.guid)
                    .subscribe(
                        (val) => {
                             this.nznot.create('success', '状态码' + val.code , val.msg);
                            if ( !(( this.total - 1) % 10)) {
                                // if ( !(( this.total - this.acfundata.length) % 10)) { // 支持批量删除的方法
                                this.system.pi -- ;
                                this.getData();
                            }
                            this.getData();

                        },
                        response => {
                            // 如果数据不正确，则在这里给初始数据
                            this.data = [];
                        });
            },
            onCancel: () => {
                console.log('取消成功');
            }
        });

    }

    deleteBatch(event) {
        this.modal.open({
            title: '是否删除',
            content: '您是否确认删除这' + event.length + '条系统参数吗?',
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
                let delarray = [];
                for( let i = 0; i < event.length; i++) {
                    delarray.push(event[i].guid);
                }
                let deletaObj = {
                    deleteList: delarray
                }
                this.utilityService.postData(appConfig.serverUrl + appConfig.API.deleteSysConfigList, deletaObj )
                    .subscribe(
                        (val) => {
                            this.getData()
                            this.selectedRows = []
                            this.nznot.create('success', val.msg , val.msg);
                        },
                        (error) => {
                            this.selectedRows = []
                            this.nznot.create('error', error.msg , error.msg);
                        });
            },
            onCancel: () => {
                this.selectedRows = []
                this.getData();
            }
        });
    }
    // 列表按钮方法
    buttonDataHandler(event) {
        console.log(event); // 根据event.value来判断不同的请求，来获取结果和方法或者进行路由的跳转
        if (event.value === 'Authority') {
            console.log(event.key);
        }

        if (event.value === 'Overview') {
            console.log(event.key);
        }

    }


    // 处理行为代码，跳转、弹出框、其他交互
    isActive(event) {
        console.log(event); // 拿到数据进行判断，是跳转路由还是弹出框弹出
        // 路由跳转
        this.router.navigate(['APPlication'], { queryParams: { name: event } });
    }


    selectedRow(event) { // 选中方法，折叠层按钮显示方法

    }


    // 搜索框
    search() {
        this.getData(this.system)
    }


    reset() {
        this.system = new SystemModule(); // 重置
        this.getData();
    }


    // selete监听方法
    checkSelect(guid) {
        this.sysAdd.value = ''
        this.isValueshow = true;
        // 根据key查询对应业务字典项
        this.utilityService.getData(appConfig.serverUrl + appConfig.API.queryListByDictId + '/' + guid)
            .subscribe(
                (val) => {
                   this.configValue = val.result;
                   console.log(this.configValue)
                }
            );
    }


    // 监听选择的参数值，绑定参数描述
    checkValueSelect(value) {

        for(let i = 0; i < this.configValue.length; i ++ ) {
            if( value === this.configValue[i].itemValue) {
                this.sysAdd.description = this.configValue[i].itemDesc; // 赋值描述
            }
        }
    }

    // select下拉选择内容
    options = [];
    selectedOption;
    index = 0;
    scrollToBottom() {
        if (!this.loading) {
            this.loading = true;
            setTimeout(() => {
                this.generateFakeData();
                this.loading = false;
            }, 3000);
        }
    }

    // 所有业务字典,不分页
    generateFakeData() {
        this.page = {
            page: {
                current: this.index,
                size: 10000, // 先写死长度
            }
        };
        // 调用服务来获取列表节点操作
        this.utilityService.postData(appConfig.serverUrl + appConfig.API.sysDictList ,  this.page)
            .subscribe(
                (val) => {
                    for (let i = 0; i < val.result.records.length; i++) {
                        this.options.push(val.result.records[i]);
                        this.index++;
                    }
                });
    }

    // 弹出框保存组件
    save(f) {
        const jsonOption = this.sysAdd;
        if (!this.isEdit) {
            this.utilityService.postData(appConfig.serverUrl + appConfig.API.sysConfigAdd, jsonOption)
                .subscribe(
                    (val) => {
                        this.nznot.create('success', val.msg , val.msg);
                        this.getData();
                    },
                    (error) => {
                        this.nznot.create('error', error.msg , error.msg);
                        this.getData();
                    });
        } else {
            this.utilityService.putData(appConfig.serverUrl + appConfig.API.sysConFigs, jsonOption)
                .subscribe(
                    (val) => {
                        this.nznot.create('success', val.msg , val.msg);
                        this.getData();
                    },
                    (error) => {
                        this.nznot.create('error', error.msg , error.msg);
                        this.getData();
                    });
        }

        this.modalVisible = false;
    }

}
